export function setCookie(key: string, value: string, time: number): void {
  let cur = new Date()
  cur.setTime(cur.getTime() + time * 24 * 3600 * 1000)
  document.cookie = `${key}=${encodeURIComponent(value)};expires=${time ? cur.toUTCString() : ''}}`
}

export function getCookie(key: string): string {
  let data = document.cookie
  let startIndex = data.indexOf(key + '=')
  if (startIndex > -1) {
    startIndex = startIndex + key.length + 1
    let endIndex = data.indexOf(';', startIndex)
    endIndex = endIndex < 0 ? data.length : endIndex
    return decodeURIComponent(data.substring(startIndex, endIndex))
  } else {
    return ''
  }
}

export function delCookie(key: string): void {
  setCookie(key, '', -1)
}

export function setSessionStorage(key: string, value: any): void {
  const str = window.JSON.stringify(value)
  window.sessionStorage.setItem(key, str)
}

export function getSessionStorage(key: string): any {
  let json: string | null
  json = window.sessionStorage.getItem(key)
  if (json) json = window.JSON.parse(json)
  return json
}

export function setLocalStorage(key: string, value: any): void {
  const str = window.JSON.stringify(value)
  window.localStorage.setItem(key, str)
}

export function getLocalStorage(key: string): any {
  let json: string | null
  json = window.localStorage.getItem(key)
  if (json) json = window.JSON.parse(json)
  return json
}
